#!/bin/sh
# STDIO mode startup script for SSH Slurm MCP Server
set -e

# Store script directory and current working directory
SCRIPT_DIR="$(dirname "$0")"
CURRENT_DIR="$(pwd)"

# Function to load and validate .env file
load_env_file() {
    local env_file="$1"
    local location="$2"
    
    if [ -f "$env_file" ]; then
        echo "Loading environment variables from $location .env file..." >&2
        
        # Check if .env file is readable and has required variables
        if grep -q "SSH_HOST" "$env_file" 2>/dev/null; then
            # Export variables from .env file
            export $(grep -v '^#' "$env_file" | grep -v '^$' | xargs)
            
            # Handle tilde expansion for SSH_KEY_PATH
            if [ -n "$SSH_KEY_PATH" ]; then
                # Expand ~ to home directory
                SSH_KEY_PATH=$(echo "$SSH_KEY_PATH" | sed "s|^~|$HOME|")
                export SSH_KEY_PATH
            fi
            echo "Successfully loaded configuration from $location" >&2
            return 0
        else
            echo "Warning: $location .env file exists but appears invalid (missing SSH_HOST)" >&2
            return 1
        fi
    fi
    return 1
}

# Try to load .env from current working directory first
if ! load_env_file "$CURRENT_DIR/.env" "current directory"; then
    # If current directory .env not found or invalid, try script directory
    load_env_file "$SCRIPT_DIR/.env" "script directory"
fi

# Change to script directory for the rest of the operations
cd "$SCRIPT_DIR"

# Create independent virtual environment (if it doesn't exist)
if [ ! -d ".venv" ]; then
    echo "Creating virtual environment..." >&2
    uv venv
    echo "Installing dependencies..." >&2
    echo "Note: Dependency installation may take several minutes. Please wait..." >&2
    uv sync 
fi

# Check necessary environment variables
if [ -z "$SSH_HOST" ]; then
    echo "Warning: SSH_HOST environment variable not set" >&2
fi

if [ -z "$SSH_USERNAME" ]; then
    echo "Warning: SSH_USERNAME environment variable not set" >&2
fi

if [ -z "$SSH_KEY_PATH" ] && [ -z "$SSH_PASSWORD" ]; then
    echo "Warning: Neither SSH_KEY_PATH nor SSH_PASSWORD environment variable set" >&2
    echo "Please set one of these for SSH authentication" >&2
fi

# Start STDIO mode MCP server
echo "Starting SSH Slurm MCP Server..." >&2
uv run python server.py --transport stdio
